package com.blackshadowgame.rps;

import com.blackshadowgame.utils.LogUtil;
import ohos.rpc.RemoteException;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class GameServiceObject extends GameServiceInterfaceStub {
    private static final String TAG = GameServiceObject.class.getSimpleName();

    private Random random = new Random();
    private static final int[] nextPlayerId = new int[]{0};

    public GameServiceObject(String descriptor){
        super(descriptor);
    }

//    private List<Integer> players = new ArrayList<>();
    private GameResultData result = new GameResultData();
    private boolean withAI = false;
    private int playerAI = 0;

    private int getRandomInput(){
        return random.nextInt(3) + 1;
    }

    @Override
    public int sendInput(int pid, int inputCode) throws RemoteException {
        boolean valid = result.addInput(pid, inputCode);
        LogUtil.info(TAG, "Player [%d] send input: [%d:%s], valid = %b", pid, inputCode, InputCode.getInputCodeName(inputCode), valid);

        if(!valid){
            return GameCode.ERROR;
        }

        if(withAI && pid != playerAI){
            // 如果是与AI对战，则在玩家输入后，AI随机输出
            sendInput(playerAI, getRandomInput());
        }

        result.calculateWinner();
        return GameCode.ERR_OK;
    }

    @Override
    public GameResultData queryGameResult(int pid) throws RemoteException {
        return result;
    }

    @Override
    public int leaveGame(int pid) throws RemoteException {
//        players.remove(pid);
        result.removePlayer(pid);

        LogUtil.info(TAG, "===> Leave Game, player: %d", pid);
        return GameCode.ERR_OK;
    }

    @Override
    public int nextGame(int pid) throws RemoteException {
        result.newGame(true);

        return GameCode.ERR_OK;
    }

    @Override
    public int echo(int a) throws RemoteException {
        return a;
    }

    @Override
    public int joinGame(String playerId) throws RemoteException {
        synchronized (nextPlayerId){
            nextPlayerId[0] += random.nextInt(100) + 1;
            LogUtil.info(TAG, "===> Join Game, new player: %d", nextPlayerId[0]);

            if(result.joinPlayer(nextPlayerId[0])){

            }
        }

        return nextPlayerId[0];
    }

    @Override
    public int playWithAI(int pid) throws RemoteException {
        if(result.hasEnoughPlayer()){
            return GameCode.ERROR;
        }

        if(!result.joinPlayer(playerAI)){
            return GameCode.ERROR;
        }else{
            withAI = true;
        }

        return GameCode.ERR_OK;
    }

    @Override
    public int[] getPlayers(int pid) throws RemoteException {
        return result.getPlayers();
    }
}
